import * as api from '@/services/checkTask';
import * as apiChecker from '@/services/checkServer';
import { DrawerForm, ProFormInstance } from '@ant-design/pro-form';
import type { ProColumns } from '@ant-design/pro-table';
import ProTable, { EditableProTable } from '@ant-design/pro-table';
import { Badge, Button, Card, Checkbox, Col, Divider, Popconfirm, Radio, Row, Tabs, Tag, message } from 'antd';
import TabPane from 'antd/lib/tabs/TabPane';
import React, { useEffect, useRef, useState } from 'react';
import * as c from '@/services/consts';
import { ProFormDatePicker, ProFormDateTimePicker, ProFormDependency, ProFormDigit, ProFormSelect, ProFormSwitch, ProFormTextArea } from '@ant-design/pro-components';
import { Space } from 'antd/lib';
import * as utils from '@/utils/utils';
import { CheckCircleFilled } from '@ant-design/icons';
import { CheckboxChangeEvent } from 'antd/es/checkbox';

type VpnServerFormProps = {
  visible: boolean;
  onCancel: () => void;
  onSubmit: () => Promise<void>;
};

const VpnServerForm: React.FC<VpnServerFormProps> = (props) => {
  const { visible, onCancel, onSubmit } =
    props;

  if (!visible) {
    return null;
  }

  // console.log(groupIds, groups, instIds, servers);

  const [myloading, setMyloading] = useState<boolean>(true);
  const [dataCheckers, setDataCheckers] = useState<API.CheckServer[] | undefined>(undefined);
  const [checkedList, setCheckedList] = useState<any[]>([]);
  // const [checkedDomainList, setCheckedDomainList] = useState<any[]>([]);
  const [checkJob, setCheckJob] = useState<string|undefined>(undefined);
  const [checkType, setCheckType] =useState<string>('1');
  
  // const [dataDomains, setDataDomains] = useState<API.CheckDomainModel[] | undefined>(undefined);

  const formRef = useRef<ProFormInstance>();

  const loadData = async () => {

    const resultChecker = await apiChecker.list();
    if (resultChecker && resultChecker.data) {
      let checkerIds = [];
      for(let d of resultChecker.data){
        if(d.isDefault == true){
          checkerIds.push(d.id);
        }
      }
      setCheckedList(checkerIds);
      setDataCheckers(resultChecker.data);
    } else {
      setDataCheckers([]);
    }

    // const resultDomains = await api.domainlist();
    // if (resultDomains && resultDomains.data) {
    //   setDataDomains(resultDomains.data);
    // } else {
    //   setDataDomains([]);
    // }

    setMyloading(false);
  };

  useEffect(() => {
    loadData();
  }, []);

  const handleSubmit = async (record: API.CheckTask) => {    
    if(!checkedList || checkedList.length == 0){
      message.error("请选择用于检测的服务器");
      return;
    }
    if(!record.job){
      message.error("请选择检测类型");
      return;
    }
    if(!record.level){
      message.error("请选择检测级别");
      return;
    }
    let customs = formRef?.current.getFieldValue("customs");
    if(!customs){
      message.error("请输入检测内容");
      return;
    }
    customs = customs.replace('\r\n', '\n').split('\n');
    record.customs = customs;
    record.serverIds = checkedList;

    const result = await api.create(record);
    if (result && result.success) {
      onSubmit();
    }
  };

  
  const checkAll = dataCheckers?.length === checkedList?.length;
  const indeterminate = checkedList?.length > 0 && checkedList?.length < dataCheckers?.length;
  const onCheckAllChange = (e: CheckboxChangeEvent) => {
    setCheckedList(e.target.checked ? dataCheckers?.map((val)=>val.id) : []);
  };


  return (
    <DrawerForm<API.CheckTask>
      open={visible}
      title='自定义检测'
      formRef={formRef}
      autoFocusFirstInput
      width={1224}
      onFinish={handleSubmit}
      drawerProps={{
        // forceRender: true,
        // destroyOnClose: true,
        // closable: false,
        onClose: onCancel,
        maskClosable: false,
      }}
      // submitter={{
      //   render: (props, defaultDoms) => {
      //     return [defaultDoms[0]];
      //   },
      // }}
    >
      
      <Row gutter={24} style={{marginTop:10}}>
        <Col span={4}>
          <ProFormSelect
            name='level'
            label="任务等级"
            allowClear={false}
            options={c.CheckLevelOptions}
            mode='single'
            initialValue={c.CheckLevel.Normal.value}
            rules={[{ required: true, message: '请选择任务等级' }]}
          />
        </Col>
        <Col span={4}>
          <ProFormSelect
            name='job'
            label="检测类型"
            allowClear={false}
            options={c.CheckJobManualOptions}
            mode='single'
            rules={[{ required: true, message: '请选择检测类型' }]}
            fieldProps={{
              listHeight:600
            }}
          />
        </Col>
        {/* <Col span={2}>
          <ProFormSwitch
            name="checkType"
            label="定时检测"
            fieldProps={{
              defaultChecked: false,
            }}
            initialValue={false}
          />
        </Col>
        <ProFormDependency name={['checkType']}>
        {(checkType) => {
          // console.log(checkType, checkType.checkType);
          if (checkType.checkType == true) {
            return (<>
                <Col span={4}>
                <ProFormDigit
                  name="interval"
                  label="检测间隔(分钟)"
                  min={1}
                  max={1000}
                  fieldProps={{ precision: 0 }}
                  rules={[{ required: true, message: '请输入检测间隔' }]}
                  allowClear={false}
                />
                </Col>
                <Col span={4}>
                  <ProFormDateTimePicker
                    name="startTime"
                    label="开始检测时间"
                  />
                </Col>
                <Col span={4}>
                  <ProFormDateTimePicker
                    name="endTime"
                    label="开始检测时间"
                  />
                </Col>
            </>);
          }
        }}
        </ProFormDependency> */}
      </Row>
      

      <Divider orientation="left" orientationMargin={0}>检测服务器</Divider>
      <Row gutter={24}>
        <Col span={24}>
          <Checkbox indeterminate={indeterminate} onChange={onCheckAllChange} checked={checkAll}>全选</Checkbox>
        </Col>
      </Row>
      <Checkbox.Group key="ckgPlat" onChange={setCheckedList} value={checkedList}>
        <Row gutter={24}>
        {dataCheckers?.map((gc) => {
          let text = <Tag color={gc.online == true ? 'green' : 'error'}>{gc.name} [{gc.id}]</Tag>;
          return (
            <Col span={6}><Checkbox value={gc.id} style={{ verticalAlign: 'middle' }}>
              {gc.status ? (
                <Badge color="#52c41a" text={text} />
              ) : (
                <Badge color="#f50" text={text} />
              )}
            </Checkbox></Col>
          );
        })}</Row>
      </Checkbox.Group>
      
      <Divider orientation="left" orientationMargin={0}>检测内容</Divider>
      <Row gutter={24}>
        <Col span={24}>
          <ProFormTextArea name="customs" 
            label="" fieldProps={{rows:20}} 
                  rules={[{ required: true, message: '请输入检测内容' }]}/>
        </Col>
      </Row>


    </DrawerForm>
  );
};

export default VpnServerForm;
